package com.xpresso.utils.email;

import java.util.ArrayList;

import javax.mail.Flags;
import javax.mail.Message;
import javax.mail.MessagingException;

import com.xpresso.utils.exceptions.XpressoException;

public class SimpleMailboxManager extends MailboxManager {

	public SimpleMailboxManager(EmailProcessor emailProcessor) {
		super(emailProcessor);
	}

	public ArrayList<ProcessedMessage> runEmailReader() throws XpressoException{
		ArrayList<ProcessedMessage> pMessages = new ArrayList<ProcessedMessage>();
		try {
			this.connect();
			Message[] messages = this.checkMail();	
			for (Message message:messages){
				ProcessedMessage pMessage = emailProcessor.processMessage(message);
				
				if (pMessage != null){
					if (pMessage.isDeleteFlag()){
						message.setFlag(Flags.Flag.DELETED, true);
					}
					pMessages.add(pMessage);
				}
			}
			
		} catch (MessagingException e) {
			throw new XpressoException("A Messaging Exception occurred", e);
		} finally {
			this.close();
		}
		return pMessages;
	}	
	
	
}
